package com.beta.cat.config.captcha;

import com.beta.cat.utils.RequestParamUtil;
import com.tencentcloudapi.captcha.v20190722.CaptchaClient;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultRequest;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.profile.Language;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TencentCaptchaService implements CaptchaAutoConfiguration.CaptchaCheckService {
    private CaptchaAutoConfiguration.CaptchaProperties properties;

    public TencentCaptchaService(CaptchaAutoConfiguration.CaptchaProperties properties) {
        this.properties = properties;
    }

    @Override
    public boolean check(String captcha, String noise) {
        //实例化认证对象，需要传参密钥
        Credential cred = new Credential(properties.getSecretId(), properties.getSecretKey());
        HttpProfile httpProfile = new HttpProfile();
        // 在外网互通的网络环境下支持http协议(默认是https协议)
        httpProfile.setProtocol("https://");
        httpProfile.setConnTimeout(10);//请求连接超时时间，单位为秒
        httpProfile.setEndpoint(properties.getEndPoint());
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        clientProfile.setLanguage(Language.EN_US);
        CaptchaClient client = new CaptchaClient(cred, "", clientProfile);
        DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest();
        req.setCaptchaType(9L);//验证码类型，填固定值9
        req.setTicket(captcha);
        req.setRandstr(noise);
        req.setUserIp(RequestParamUtil.getIpAdress());
        req.setCaptchaAppId(properties.getLongSetting("captchaAppId"));
        req.setAppSecretKey(properties.getStrSetting("appSecretKey"));
        req.setBusinessId(properties.getLongSetting("businessId"));
        req.setSceneId(properties.getLongSetting("sceneId"));
        req.setNeedGetCaptchaTime(1L);//是否返回前端获取验证码时间，取值1：需要返回
        try {
            DescribeCaptchaResultResponse response = client.DescribeCaptchaResult(req);
            if (response.getCaptchaCode() == null || response.getCaptchaCode() != 1L) {
                log.info("CaptchaUtil checkCaptcha 腾讯验证码验证失败。code:{},msg:{}", response.getCaptchaCode(), response.getCaptchaMsg());
                return false;
            }
            return true;
        } catch (TencentCloudSDKException e) {
            log.error("CaptchaUtil checkCaptcha 腾讯验证码验证异常。code:{},msg:{}", e.getErrorCode(), e.getMessage());
            return false;
        }
    }
}
